<template>
  <div style="margin: 30px auto;width: 99%;">
    <div>
      <el-form ref="ruleForm2" :model="appForm" :rules="rules2" class="demo-ruleForm" :inline="true">
        <el-form-item label="应用名称" prop="appname" label-width="100px">
          <el-input type="text" v-model="appForm.appname" auto-complete="off" style="width:300px;"
                    placeholder="输入应用名称查询应用"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm2')">查询</el-button>
          <el-button @click="resetForm('ruleForm2')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      empty-text="暂无应用信息"
      style="width: 100%;text-align: center"
      :data="appInfos"
      border>
      <el-table-column
        prop="appName"
        header-align="center"
        :show-overflow-tooltip="true"
        label="应用名称"
        width="200">
      </el-table-column>
      <el-table-column
        header-align="center"
        :show-overflow-tooltip="true"
        prop="mqAccessKey"
        label="mqAccessKey"
        width="200">
      </el-table-column>
      <el-table-column
        header-align="center"
        :show-overflow-tooltip="true"
        prop="mqSecretKey"
        label="mqSecretKey"
        width="200">
      </el-table-column>
      <el-table-column
        header-align="center"
        :show-overflow-tooltip="true"
        prop="mqConsumerId"
        label="mqConsumerId"
        width="200">
      </el-table-column>
      <el-table-column
        header-align="center"
        :show-overflow-tooltip="true"
        prop="token"
        label="应用token"
        width="200">
      </el-table-column>
      <el-table-column
        header-align="center"
        :show-overflow-tooltip="true"
        prop="description"
        label="描述信息"
        width="200">
      </el-table-column>
      <el-table-column :render-header="renderHeader" header-align="center" fixed="right" width="180">
        <template scope="scope">
          <el-button size="small" @click="showLookAppDialog(appInfos[scope.$index])">查看</el-button>
          <el-button size="small" @click="showEditAppDialog(appInfos[scope.$index])">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="注册新应用" :visible.sync="addAppDialogVisible" size="" top="10%">
      <el-form ref="form" :model="form" :rules="rule">
        <el-form-item label="应用名称" prop="name" style="width: 600px">
          <el-input v-model="form.name" placeholder="英文名称"></el-input>
        </el-form-item>
        <el-form-item label="mqAccessKey" prop="mqAccessKey" style="width: 600px">
          <el-input v-model="form.mqAccessKey"></el-input>
        </el-form-item>
        <el-form-item label="mqSecretKey" prop="mqSecretKey" style="width: 600px">
          <el-input v-model="form.mqSecretKey"></el-input>
        </el-form-item>
        <el-form-item label="mqConsumerId" prop="mqConsumerId" style="width: 600px">
          <el-input v-model="form.mqConsumerId"></el-input>
        </el-form-item>
        <el-form-item label="管理员" prop="empIds" style="width: 600px">
          <el-select v-model="form.empIds" multiple placeholder="请选择管理员" style="width: 100%" filterable>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述信息" prop="description" style="width: 600px">
          <el-input
            type="textarea"
            autosize
            :autosize="{ minRows: 1, maxRows: 4}"
            placeholder="请输入描述信息"
            v-model="form.description">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitRegisterAppInfo('form')">确 定</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
        <el-button @click="addAppDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看应用信息" :visible.sync="lookAppDialogVisible" size="" top="10%" :show-close="true">
      <el-form ref="appInfoForm" :model="appInfoForm">
        <el-form-item label="应用名称" prop="name" style="width: 600px">
          <el-input v-model="appInfoForm.name" placeholder="英文名称" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="mqAccessKey" prop="mqAccessKey" style="width: 600px">
          <el-input v-model="appInfoForm.mqAccessKey" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="mqSecretKey" prop="mqSecretKey" style="width: 600px">
          <el-input v-model="appInfoForm.mqSecretKey" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="mqConsumerId" prop="mqConsumerId" style="width: 600px">
          <el-input v-model="appInfoForm.mqConsumerId" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="管理员" prop="empIds" style="width: 600px">
          <el-input v-model="appInfoForm.empIds"></el-input>
        </el-form-item>
        <el-form-item label="描述信息" prop="description" style="width: 600px">
          <el-input
            type="textarea"
            autosize
            :readonly="true"
            :autosize="{ minRows: 1, maxRows: 4}"
            v-model="appInfoForm.description">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="修改应用信息" :visible.sync="editAppDialogVisible" size="" top="10%" :show-close="true">
      <el-form ref="appEditInfoForm" :model="appEditInfoForm">
        <el-form-item label="应用名称" prop="name" style="width: 600px">
          <el-input v-model="appEditInfoForm.name" placeholder="英文名称" disabled></el-input>
        </el-form-item>
        <el-form-item label="mqAccessKey" prop="mqAccessKey" style="width: 600px">
          <el-input v-model="appEditInfoForm.mqAccessKey"></el-input>
        </el-form-item>
        <el-form-item label="mqSecretKey" prop="mqSecretKey" style="width: 600px">
          <el-input v-model="appEditInfoForm.mqSecretKey"></el-input>
        </el-form-item>
        <el-form-item label="mqConsumerId" prop="mqConsumerId" style="width: 600px">
          <el-input v-model="appEditInfoForm.mqConsumerId"></el-input>
        </el-form-item>
        <el-form-item label="描述信息" prop="description" style="width: 600px">
          <el-input
            type="textarea"
            autosize
            :autosize="{ minRows: 1, maxRows: 4}"
            v-model="appEditInfoForm.description">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitEditAppInfo('appEditInfoForm')">确 定</el-button>
        <el-button @click="editAppDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<style scoped>
  .form {
    margin: 10px auto;
    width: 80%;
  }
  .item {
    margin-top: 10px;
    margin-right: 40px;
  }
</style>
<script>
  import {mapState} from 'vuex';
  import fetch from "../../store/uacc_api";
  export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入应用名称'));
        } else {
          callback();
        }
      };
      return {
        addAppDialogVisible: false,
        lookAppDialogVisible: false,
        editAppDialogVisible: false,
        appInfos: [],
        options: [],
        appForm: {
          appname: ''
        },
        rules2: {
          appname: [
            {validator: validatePass, trigger: 'blur'}
          ]
        },
        rule: {
          name: [
            {required: true, message: '名称不能为空', trigger: 'blur'},
            {message: '名称只能是字母或者数字', pattern: (/^[0-9a-zA-Z]+$/), trigger: 'blur'},
          ],
          mqConsumerId: [
            {required: true, message: '请输入消费者id', trigger: 'blur'}
          ],
          descrition: [
            {required: true, message: '请输入应用描述', trigger: 'blur'},
          ],
          mqAccessKey: [
            {required: true, message: '请输入密码', trigger: 'blur'},
          ],
          mqSecretKey: [
            {required: true, message: '请输入秘钥', trigger: 'blur'},
          ],
          empIds: [
            {required: true, type: 'array', message: '请选择管理员', trigger: 'blur'},
          ],
          description: [
            {required: true, message: '请输入描述信息', trigger: 'blur'},
          ]
        },
        form: {
          name: '',
          descrition: '',
          description: '',
          mqAccessKey: '',
          mqSecretKey: '',
          mqConsumerId: '',
          empIds: []
        },
        appInfoForm: {
          name: '',
          descrition: '',
          description: '',
          mqAccessKey: '',
          mqSecretKey: '',
          mqConsumerId: '',
          empIds: ''
        },
        appEditInfoForm: {
          name: '',
          descrition: '',
          description: '',
          mqAccessKey: '',
          mqSecretKey: '',
          mqConsumerId: '',
          empIds: ''
        }
      }
    },
    computed: {
      ...mapState(['currentUser']),
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let me = this;
            this.appInfos = [];
            fetch.queryAppByName({appName: this.appForm.appname}).then(function (res) {
              if (res.success) {
                console.info(res.data);
                me.appInfos.push(res.data);
                console.info(me.appInfos);
              } else {
                me.$message({
                  showClose: true,
                  message: res.errorMessage,
                  type: 'error'
                });
              }
            })
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      renderHeader(createElement) {
        return createElement(
          'div',
          {
            'class': 'renderTableHead'
          },
          [
            createElement('el-tag', {
                style: {'margin-right': '20px'},
                attrs: {type: 'info', plain: true, size: 'small'},
              }, ['操作']
            ),
            createElement('el-button', {
                attrs: {type: 'danger', icon:'upload2', size: 'small'},
                on: {click: this.showRegisterAppDialog}
              }, ['注册应用']
            )
          ]
        );
      },
      showRegisterAppDialog(){
        this.options = [];
        this.form.empIds = [];
        this.getAllUsers();
        this.addAppDialogVisible = true;
      },
      getAllUsers(){
        //查询所有用户列表
        let me = this;
        fetch.getAllUser().then(function (res) {
          if (res.success) {
            let allUser = res.data;
            me.form.empIds.push(me.currentUser.empId);
            allUser.forEach((user) => {
              me.options.push({
                label: user.nickName,
                value: user.empId
              })
            });
          }
        });
      },
      onSubmitRegisterAppInfo(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let emps = '';
            if (this.form.empIds) {
              this.form.empIds.forEach(function (emp) {
                emps = emps + emp + ',';
              });
              emps = emps.substring(0, emps.length - 1);
            }
            let app = {
              appName: this.form.name,
              description: this.form.description,
              mqAccessKey: this.form.mqAccessKey,
              mqSecretKey: this.form.mqSecretKey,
              mqConsumerId: this.form.mqConsumerId,
              empIds: emps
            };
            let param = {'data': encodeURIComponent(JSON.stringify(app))};
            this.registerApp(param);

          } else {
            return false;
          }
        });
      },
      registerApp(param){
        this.addAppDialogVisible = false;
        let me = this;
        fetch.registerApp(param).then(function (res) {
          if (res.success) {
            me.$message({
              showClose: true,
              type: 'success',
              message: '应用注册成功'
            });
            me.resetForm('form');
          } else {
            me.$message({
              showClose: true,
              message: res.errorMessage,
              type: 'error'
            });
          }
        })
      },
      showLookAppDialog(app){
        this.appInfoForm.name = app.appName;
        this.appInfoForm.description = app.description;
        this.appInfoForm.mqAccessKey = app.mqAccessKey;
        this.appInfoForm.mqSecretKey = app.mqSecretKey;
        this.appInfoForm.mqConsumerId = app.mqConsumerId;
        this.appInfoForm.empIds = app.empIds;
        this.lookAppDialogVisible = true;
      },
      showEditAppDialog(app){
        console.info(app);
        this.appEditInfoForm.name = app.appName;
        this.appEditInfoForm.description = app.description;
        this.appEditInfoForm.mqAccessKey = app.mqAccessKey;
        this.appEditInfoForm.mqSecretKey = app.mqSecretKey;
        this.appEditInfoForm.mqConsumerId = app.mqConsumerId;
        this.appEditInfoForm.empIds = app.empIds;
        this.editAppDialogVisible = true;
      },
      onSubmitEditAppInfo(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let app = {
              appName: this.appEditInfoForm.name,
              description: this.appEditInfoForm.description,
              mqAccessKey: this.appEditInfoForm.mqAccessKey,
              mqSecretKey: this.appEditInfoForm.mqSecretKey,
              mqConsumerId: this.appEditInfoForm.mqConsumerId,
              empIds: this.appEditInfoForm.empIds
            };
            console.info(app);
            let param = {'data': encodeURIComponent(JSON.stringify(app))};
            this.updateApp(param);
          } else {
            return false;
          }
        });
      },
      updateApp(param){
        this.editAppDialogVisible = false;
        let me = this;
        fetch.updateApp(param).then(function (res) {
          if (res.success) {
            me.$message({
              showClose: true,
              type: 'success',
              message: '修改应用信息成功'
            });
            me.submitForm('ruleForm2');
          } else {
            me.$message({
              showClose: true,
              message: res.errorMessage,
              type: 'error'
            });
          }
        })
      }
    }
  }
</script>
